package com.peng.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.mapper.AdminMapper;
import com.peng.pojo.Admin;
import com.peng.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.w3c.dom.ls.LSInput;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class AuthService {
    @Autowired
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication){
        String requestURI = request.getRequestURI();
        Object principal = authentication.getPrincipal();
        if (principal==null || "anonymousUser".equals(principal)){
            return false;
        }
        UserDetails userDetails= (UserDetails) principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findUserByName(username);
        if (admin==null){
            return false;
        }
        if (admin.getId()==1){
            return true;
        }
        List<Permission> permissions= adminService.findPermissionAdminId(admin.getId());
        String s = StringUtils.split(requestURI, '?')[0];
        for (Permission permission : permissions) {
            if (permission.getPath().equals(s)){
                return true;
            }
        }
        return false;
    }
}
